/**
 * bankcards.js - 银行卡管理页面脚本
 */

// 全局变量
let bankcards = [];
let currentCardId = null;

document.addEventListener('DOMContentLoaded', function() {
  // 页面初始化
  const pageLayout = new PageLayout();
  pageLayout.init('bankcards');
  
  // 初始化模态框事件
  initModals();
  
  // 加载银行卡列表
  loadBankcards();
  
  // 绑定添加银行卡按钮事件
  document.getElementById('add-bankcard-btn').addEventListener('click', openAddBankcardModal);
  
  // 绑定银行卡类型切换事件
  const cardTypeSelect = document.getElementById('card-type');
  cardTypeSelect.addEventListener('change', function() {
    const creditCardFields = document.getElementById('credit-card-fields');
    if (this.value === '2') { // 信用卡
      creditCardFields.style.display = 'block';
    } else { // 储蓄卡
      creditCardFields.style.display = 'none';
    }
  });
  
  // 绑定保存银行卡按钮事件
  document.getElementById('save-bankcard-btn').addEventListener('click', saveBankcard);
});

/**
 * 初始化模态框
 */
function initModals() {
  // 添加银行卡模态框
  const addModal = document.getElementById('add-bankcard-modal');
  const addModalCloseButtons = addModal.querySelectorAll('.modal-close, .btn[data-dismiss="modal"]');
  
  addModalCloseButtons.forEach(button => {
    button.addEventListener('click', () => {
      addModal.style.display = 'none';
      resetAddBankcardForm();
    });
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', (event) => {
    if (event.target === addModal) {
      addModal.style.display = 'none';
      resetAddBankcardForm();
    }
  });
  
  // 确认删除模态框
  const deleteModal = document.getElementById('confirm-delete-modal');
  const deleteModalCloseButtons = deleteModal.querySelectorAll('.modal-close, .btn[data-dismiss="modal"]');
  
  deleteModalCloseButtons.forEach(button => {
    button.addEventListener('click', () => {
      deleteModal.style.display = 'none';
    });
  });
  
  // 点击模态框外部关闭
  window.addEventListener('click', (event) => {
    if (event.target === deleteModal) {
      deleteModal.style.display = 'none';
    }
  });
  
  // 确认删除按钮
  document.getElementById('confirm-delete-btn').addEventListener('click', deleteBankcard);
}

/**
 * 加载银行卡列表
 */
function loadBankcards() {
  const bankcardList = document.getElementById('bankcard-list');
  
  // 显示加载中
  bankcardList.innerHTML = `
    <div class="loader-container">
      <div class="loader"></div>
    </div>
  `;
  
  // 调用API获取银行卡列表
  ApiService.get('/api/bankcard/list')
    .then(response => {
      if (response.code === 0 && response.data) {
        bankcards = response.data || [];
        renderBankcards();
      } else {
        throw new Error(response.message || '获取银行卡列表失败');
      }
    })
    .catch(error => {
      console.error('获取银行卡列表失败:', error);
      bankcardList.innerHTML = `
        <div class="empty-state">
          <i class="fas fa-credit-card mb-3" style="font-size: 48px; color: var(--light-text);"></i>
          <p>加载银行卡失败，请稍后再试</p>
          <button class="btn btn-primary mt-3" id="retry-load-btn">重试</button>
        </div>
      `;
      
      // 添加重试按钮事件
      const retryBtn = document.getElementById('retry-load-btn');
      if (retryBtn) {
        retryBtn.addEventListener('click', loadBankcards);
      }
    });
}

/**
 * 渲染银行卡列表
 */
function renderBankcards() {
  const bankcardList = document.getElementById('bankcard-list');
  
  if (bankcards.length === 0) {
    bankcardList.innerHTML = `
      <div class="empty-state">
        <i class="fas fa-credit-card mb-3" style="font-size: 48px; color: var(--light-text);"></i>
        <p>您还没有添加银行卡</p>
        <button class="btn btn-primary mt-3" id="empty-add-btn">添加银行卡</button>
      </div>
    `;
    
    // 添加添加银行卡按钮事件
    const emptyAddBtn = document.getElementById('empty-add-btn');
    if (emptyAddBtn) {
      emptyAddBtn.addEventListener('click', openAddBankcardModal);
    }
    
    return;
  }
  
  let bankcardHtml = '';
  
  // 渲染银行卡列表
  bankcards.forEach(card => {
    // 卡片样式
    const cardClass = card.cardType === 1 ? 'debit' : 'credit';
    
    // 卡号脱敏展示
    const maskedCardNumber = maskCardNumber(card.cardNumber);
    
    // 默认卡标记
    const defaultBadge = card.isDefault === 1 ? 
      '<div class="bankcard-default-badge">默认卡</div>' : '';
    
    // 有效期（仅信用卡）
    const expireDate = card.cardType === 2 && card.expireDate ? 
      `<div class="bankcard-expire">有效期至：${card.expireDate}</div>` : '';
    
    // 卡片图标
    const cardIcon = card.cardType === 1 ? 
      '<i class="fas fa-money-check-alt"></i>' : '<i class="far fa-credit-card"></i>';
    
    bankcardHtml += `
      <div class="bankcard ${cardClass}" data-id="${card.id}">
        ${defaultBadge}
        <div class="bankcard-chip"></div>
        <div class="bankcard-bank-name">${card.bankName}</div>
        <div class="bankcard-number">${maskedCardNumber}</div>
        <div class="bankcard-name">
          <span>${card.cardholderName}</span>
          <span>${card.cardType === 1 ? '储蓄卡' : '信用卡'}</span>
        </div>
        ${expireDate}
        <div class="bankcard-type-icon">${cardIcon}</div>
        <div class="bankcard-actions">
          ${card.isDefault !== 1 ? 
            `<div class="bankcard-action set-default" data-id="${card.id}" title="设为默认">
              <i class="fas fa-star"></i>
            </div>` : ''}
          <div class="bankcard-action delete" data-id="${card.id}" title="删除">
            <i class="fas fa-trash-alt"></i>
          </div>
        </div>
      </div>
    `;
  });
  
  // 添加"添加银行卡"卡片
  bankcardHtml += `
    <div class="add-bankcard-card" id="add-card-button">
      <div class="add-bankcard-icon">
        <i class="fas fa-plus"></i>
      </div>
      <div class="add-bankcard-text">添加银行卡</div>
    </div>
  `;
  
  bankcardList.innerHTML = bankcardHtml;
  
  // 绑定按钮事件
  
  // 添加银行卡按钮
  document.getElementById('add-card-button').addEventListener('click', openAddBankcardModal);
  
  // 设为默认按钮
  document.querySelectorAll('.bankcard-action.set-default').forEach(button => {
    button.addEventListener('click', (event) => {
      event.stopPropagation();
      const cardId = button.getAttribute('data-id');
      setDefaultBankcard(cardId);
    });
  });
  
  // 删除按钮
  document.querySelectorAll('.bankcard-action.delete').forEach(button => {
    button.addEventListener('click', (event) => {
      event.stopPropagation();
      const cardId = button.getAttribute('data-id');
      openDeleteConfirmModal(cardId);
    });
  });
}

/**
 * 打开添加银行卡模态框
 */
function openAddBankcardModal() {
  // 重置表单
  resetAddBankcardForm();
  
  // 显示模态框
  document.getElementById('add-bankcard-modal').style.display = 'block';
}

/**
 * 重置添加银行卡表单
 */
function resetAddBankcardForm() {
  const form = document.getElementById('add-bankcard-form');
  form.reset();
  
  // 重置错误提示
  document.querySelectorAll('.form-error').forEach(error => {
    error.textContent = '';
  });
  
  // 重置信用卡字段显示状态
  document.getElementById('credit-card-fields').style.display = 'none';
}

/**
 * 验证银行卡表单
 * @returns {boolean} 验证结果
 */
function validateBankcardForm() {
  let isValid = true;
  
  // 验证卡号
  const cardNumber = document.getElementById('card-number').value.trim();
  const cardNumberError = document.getElementById('card-number-error');
  
  if (!cardNumber) {
    cardNumberError.textContent = '请输入卡号';
    isValid = false;
  } else if (!/^\d{16,19}$/.test(cardNumber)) {
    cardNumberError.textContent = '卡号格式不正确，应为16-19位数字';
    isValid = false;
  }
  
  // 验证持卡人姓名
  const cardholderName = document.getElementById('cardholder-name').value.trim();
  const cardholderNameError = document.getElementById('cardholder-name-error');
  
  if (!cardholderName) {
    cardholderNameError.textContent = '请输入持卡人姓名';
    isValid = false;
  }
  
  // 验证信用卡特有字段
  const cardType = document.getElementById('card-type').value;
  
  if (cardType === '2') { // 信用卡
    // 验证有效期
    const expireDate = document.getElementById('expire-date').value.trim();
    const expireDateError = document.getElementById('expire-date-error');
    
    if (!expireDate) {
      expireDateError.textContent = '请输入有效期';
      isValid = false;
    } else if (!/^\d{2}\/\d{2}$/.test(expireDate)) {
      expireDateError.textContent = '有效期格式不正确，应为MM/YY';
      isValid = false;
    }
    
    // 验证安全码
    const cvv = document.getElementById('cvv').value.trim();
    const cvvError = document.getElementById('cvv-error');
    
    if (!cvv) {
      cvvError.textContent = '请输入安全码';
      isValid = false;
    } else if (!/^\d{3}$/.test(cvv)) {
      cvvError.textContent = '安全码格式不正确，应为3位数字';
      isValid = false;
    }
  }
  
  // 验证手机号
  const bindPhone = document.getElementById('bind-phone').value.trim();
  const bindPhoneError = document.getElementById('bind-phone-error');
  
  if (!bindPhone) {
    bindPhoneError.textContent = '请输入绑定手机号';
    isValid = false;
  } else if (!/^\d{11}$/.test(bindPhone)) {
    bindPhoneError.textContent = '手机号格式不正确，应为11位数字';
    isValid = false;
  }
  
  return isValid;
}

/**
 * 保存银行卡
 */
function saveBankcard() {
  // 表单验证
  if (!validateBankcardForm()) {
    return;
  }
  
  // 获取表单数据
  const cardNumber = document.getElementById('card-number').value.trim();
  const cardType = parseInt(document.getElementById('card-type').value);
  const bankName = document.getElementById('bank-name').value;
  const cardholderName = document.getElementById('cardholder-name').value.trim();
  const bindPhone = document.getElementById('bind-phone').value.trim();
  const isDefault = document.getElementById('is-default').checked ? 1 : 0;
  
  // 信用卡特有字段
  let expireDate = null;
  let cvv = null;
  
  if (cardType === 2) { // 信用卡
    expireDate = document.getElementById('expire-date').value.trim();
    cvv = document.getElementById('cvv').value.trim();
  }
  
  // 构建请求数据
  const bankcardData = {
    cardNumber,
    cardType,
    bankName,
    cardholderName,
    bindPhone,
    isDefault
  };
  
  if (cardType === 2) {
    bankcardData.expireDate = expireDate;
    bankcardData.cvv = cvv;
  }
  
  // 调用添加银行卡API
  ApiService.post('/api/bankcard/add', bankcardData)
    .then(response => {
      if (response.code === 0 && response.data) {
        // 关闭模态框
        document.getElementById('add-bankcard-modal').style.display = 'none';
        
        // 显示成功提示
        Toast.success('银行卡添加成功');
        
        // 重新加载银行卡列表
        loadBankcards();
      } else {
        throw new Error(response.message || '添加银行卡失败');
      }
    })
    .catch(error => {
      console.error('添加银行卡失败:', error);
      Toast.error('添加银行卡失败: ' + error.message);
    });
}

/**
 * 打开删除确认模态框
 * @param {string} cardId 银行卡ID
 */
function openDeleteConfirmModal(cardId) {
  // 设置当前操作的卡ID
  currentCardId = cardId;
  
  // 显示确认模态框
  document.getElementById('confirm-delete-modal').style.display = 'block';
}

/**
 * 删除银行卡
 */
function deleteBankcard() {
  if (!currentCardId) {
    Toast.error('操作失败，请刷新页面后重试');
    return;
  }
  
  // 调用删除银行卡API
  ApiService.delete(`/api/bankcard/${currentCardId}`)
    .then(response => {
      if (response.code === 0 && response.data) {
        // 关闭模态框
        document.getElementById('confirm-delete-modal').style.display = 'none';
        
        // 显示成功提示
        Toast.success('银行卡删除成功');
        
        // 重新加载银行卡列表
        loadBankcards();
      } else {
        throw new Error(response.message || '删除银行卡失败');
      }
    })
    .catch(error => {
      console.error('删除银行卡失败:', error);
      Toast.error('删除银行卡失败: ' + error.message);
      
      // 关闭模态框
      document.getElementById('confirm-delete-modal').style.display = 'none';
    });
}

/**
 * 设置默认银行卡
 * @param {string} cardId 银行卡ID
 */
function setDefaultBankcard(cardId) {
  // 构建请求数据
  const data = {
    isDefault: 1
  };
  
  // 调用API
  ApiService.put(`/api/bankcard/${cardId}/default`, data)
    .then(response => {
      if (response.code === 0 && response.data) {
        // 显示成功提示
        Toast.success('默认银行卡设置成功');
        
        // 重新加载银行卡列表
        loadBankcards();
      } else {
        throw new Error(response.message || '设置默认银行卡失败');
      }
    })
    .catch(error => {
      console.error('设置默认银行卡失败:', error);
      Toast.error('设置默认银行卡失败: ' + error.message);
    });
}

/**
 * 银行卡号脱敏处理
 * @param {string} cardNumber 原始卡号
 * @returns {string} 脱敏后的卡号
 */
function maskCardNumber(cardNumber) {
  if (!cardNumber) return '';
  
  // 保留前4位和后4位，中间用*替代
  const firstPart = cardNumber.substring(0, 4);
  const lastPart = cardNumber.substring(cardNumber.length - 4);
  const middlePart = '*'.repeat(Math.min(8, cardNumber.length - 8));
  
  return `${firstPart} ${middlePart} ${lastPart}`;
}
